import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../model/health_record.dart';
import '../service/database_service.dart';
import 'base_record_dialog.dart';

class AddTemperatureRecordDialog extends BaseRecordDialog {
  const AddTemperatureRecordDialog({Key? key, required String babyId})
    : super(key: key, babyId: babyId);

  @override
  _AddTemperatureRecordDialogState createState() =>
      _AddTemperatureRecordDialogState();
}

class _AddTemperatureRecordDialogState
    extends BaseRecordDialogState<AddTemperatureRecordDialog> {
  double temperature = 37.0;

  @override
  String getDialogTitle() => '记录体温';

  @override
  Widget buildCustomContent(BuildContext context) {
    return TextField(
      decoration: InputDecoration(
        labelText: '体温',
        suffixText: '°C',
        border: OutlineInputBorder(),
      ),
      keyboardType: TextInputType.numberWithOptions(decimal: true),
      onChanged: (value) => temperature = double.tryParse(value) ?? 37.0,
    );
  }

  @override
  Future<void> saveRecord(BuildContext context) async {
    if (temperature < 35.0 || temperature > 42.0) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('请输入有效的体温值')));
      return;
    }

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.temperature,
          timestamp: selectedDateTime,
          data: {'temperature': temperature, 'notes': notes},
        ),
      );
      Navigator.pop(context);
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
    }
  }
}
